<?php
/**
 * 后台常用观众信息管理API
 * 支持常用观众信息的查看、编辑、删除等功能
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 简单的token验证
function verifyAdminToken($token) {
    global $pdo;
    
    if (empty($token)) {
        return false;
    }
    
    // 移除Bearer前缀
    if (strpos($token, 'Bearer ') === 0) {
        $token = substr($token, 7);
    }
    
    try {
        $sql = "SELECT au.*, ar.permissions 
                FROM admin_users au 
                LEFT JOIN admin_roles ar ON au.role_id = ar.id 
                WHERE au.id = ? AND au.status = 'active'";
        $stmt = $pdo->prepare($sql);
        // 简化token验证，实际应该有更复杂的验证逻辑
        $stmt->execute([1]); // 临时使用admin用户
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return false;
    }
}

// 获取认证token
function getAuthToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        return substr($authHeader, 7);
    }
    
    return $_GET['token'] ?? $_POST['token'] ?? '';
}

// 验证管理员权限
$token = getAuthToken();
$admin = verifyAdminToken($token);

if (!$admin) {
    error('未授权的访问', 401);
}

// 获取常用观众信息列表
function getVisitorList() {
    global $pdo;
    
    try {
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = min(100, max(10, (int)($_GET['limit'] ?? 50)));
        $offset = ($page - 1) * $limit;
        
        // 构建查询条件
        $where = "1=1";
        $params = [];
        
        // 证件类型筛选
        if (isset($_GET['id_type']) && !empty($_GET['id_type'])) {
            $where .= " AND cv.id_type = ?";
            $params[] = $_GET['id_type'];
        }
        
        // 关键词搜索
        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $where .= " AND (cv.name LIKE ? OR cv.id_number LIKE ? OR cv.phone LIKE ?)";
            $params[] = '%' . $_GET['search'] . '%';
            $params[] = '%' . $_GET['search'] . '%';
            $params[] = '%' . $_GET['search'] . '%';
        }
        
        // 按用户ID筛选
        if (isset($_GET['user_id']) && is_numeric($_GET['user_id'])) {
            $where .= " AND cv.user_id = ?";
            $params[] = $_GET['user_id'];
        }
        
        // 查询总数
        $countSql = "SELECT COUNT(*) FROM common_visitors cv WHERE $where";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetchColumn();
        
        // 构建完整的SQL查询
        $baseSql = "SELECT 
                    cv.id,
                    cv.user_id,
                    cv.name,
                    cv.id_type,
                    cv.id_number,
                    cv.phone,
                    cv.created_at,
                    cv.updated_at,
                    u.nickname as user_nickname,
                    u.real_name as user_real_name,
                    u.avatar as user_avatar,
                    u.openid as user_openid
                FROM common_visitors cv
                LEFT JOIN users u ON cv.user_id = u.id
                WHERE $where
                ORDER BY cv.updated_at DESC";
        
        // 添加LIMIT和OFFSET，确保它们是整数
        $limitInt = intval($limit);
        $offsetInt = intval($offset);
        $sql = $baseSql . sprintf(" LIMIT %d OFFSET %d", $limitInt, $offsetInt);
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $visitors = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 格式化数据
        foreach ($visitors as &$visitor) {
            // 用户信息
            $visitor['user_name'] = $visitor['user_real_name'] ?: $visitor['user_nickname'] ?: '未知用户';
            
            // 脱敏处理身份证号码
            if (strlen($visitor['id_number']) > 6) {
                $visitor['id_number_masked'] = substr($visitor['id_number'], 0, 3) . 
                                             str_repeat('*', strlen($visitor['id_number']) - 6) . 
                                             substr($visitor['id_number'], -3);
            } else {
                $visitor['id_number_masked'] = $visitor['id_number'];
            }
            
            // 脱敏处理手机号
            if (strlen($visitor['phone']) == 11) {
                $visitor['phone_masked'] = substr($visitor['phone'], 0, 3) . '****' . substr($visitor['phone'], -4);
            } else {
                $visitor['phone_masked'] = $visitor['phone'];
            }
        }
        
        success([
            'list' => $visitors,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => (int)$total,
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取观众信息列表失败: ' . $e->getMessage(), 500);
    }
}

// 获取常用观众信息详情
function getVisitorDetail() {
    global $pdo;
    
    $id = $_GET['id'] ?? 0;
    if (!$id) {
        error('缺少观众信息ID');
    }
    
    try {
        $sql = "SELECT 
                    cv.*,
                    u.nickname as user_nickname,
                    u.real_name as user_real_name,
                    u.phone as user_phone,
                    u.avatar as user_avatar,
                    u.openid as user_openid
                FROM common_visitors cv
                LEFT JOIN users u ON cv.user_id = u.id
                WHERE cv.id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        $visitor = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$visitor) {
            error('观众信息不存在');
        }
        
        // 用户信息
        $visitor['user_name'] = $visitor['user_real_name'] ?: $visitor['user_nickname'] ?: '未知用户';
        
        // 查询使用次数（在团队预约和活动申请中的使用情况）
        $usageSql = "SELECT 
                        'team_reservation' as type,
                        COUNT(*) as count,
                        MAX(created_at) as last_used
                     FROM team_reservations 
                     WHERE contact_name = ? AND contact_phone = ?
                     UNION ALL
                     SELECT 
                        'activity_application' as type,
                        COUNT(*) as count,
                        MAX(created_at) as last_used
                     FROM activity_applications 
                     WHERE contact_name = ? AND contact_phone = ?";
        $usageStmt = $pdo->prepare($usageSql);
        $usageStmt->execute([
            $visitor['name'], $visitor['phone'],
            $visitor['name'], $visitor['phone']
        ]);
        $usage = $usageStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $visitor['usage_stats'] = $usage;
        
        success($visitor);
        
    } catch (Exception $e) {
        error('获取观众信息详情失败: ' . $e->getMessage(), 500);
    }
}

// 更新常用观众信息
function updateVisitor() {
    global $pdo, $admin;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $id = $input['id'] ?? 0;
    $name = trim($input['name'] ?? '');
    $idType = trim($input['id_type'] ?? '身份证');
    $idNumber = trim($input['id_number'] ?? '');
    $phone = trim($input['phone'] ?? '');
    
    if (!$id) {
        error('缺少观众信息ID');
    }
    
    if (!$name) {
        error('请输入姓名');
    }
    
    if (!$idNumber) {
        error('请输入证件号码');
    }
    
    // 验证手机号格式
    if ($phone && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
        error('手机号格式不正确');
    }
    
    // 验证身份证号格式（如果是身份证）
    if ($idType == '身份证' && !preg_match('/^\d{17}[\dX]$/', $idNumber)) {
        error('身份证号格式不正确');
    }
    
    try {
        $pdo->beginTransaction();
        
        // 检查是否存在
        $checkSql = "SELECT name FROM common_visitors WHERE id = ?";
        $checkStmt = $pdo->prepare($checkSql);
        $checkStmt->execute([$id]);
        $oldVisitor = $checkStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$oldVisitor) {
            throw new Exception('观众信息不存在');
        }
        
        // 检查同用户下是否有重复的证件号
        $duplicateSql = "SELECT id FROM common_visitors 
                        WHERE user_id = (SELECT user_id FROM common_visitors WHERE id = ?) 
                        AND id_number = ? AND id != ?";
        $duplicateStmt = $pdo->prepare($duplicateSql);
        $duplicateStmt->execute([$id, $idNumber, $id]);
        if ($duplicateStmt->fetch()) {
            throw new Exception('该用户已存在相同证件号的观众信息');
        }
        
        // 更新观众信息
        $sql = "UPDATE common_visitors SET 
                    name = ?, 
                    id_type = ?,
                    id_number = ?,
                    phone = ?,
                    updated_at = NOW() 
                WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $idType, $idNumber, $phone, $id]);
        
        // 记录操作日志
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '更新常用观众信息',
            'common_visitors',
            "更新了观众信息：「{$oldVisitor['name']}」",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(null, '更新成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('更新失败: ' . $e->getMessage(), 500);
    }
}

// 删除常用观众信息
function deleteVisitor() {
    global $pdo, $admin;
    
    $id = $_GET['id'] ?? 0;
    if (!$id) {
        error('缺少观众信息ID');
    }
    
    try {
        $pdo->beginTransaction();
        
        // 先获取观众信息用于日志
        $visitorSql = "SELECT name FROM common_visitors WHERE id = ?";
        $visitorStmt = $pdo->prepare($visitorSql);
        $visitorStmt->execute([$id]);
        $visitor = $visitorStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$visitor) {
            throw new Exception('观众信息不存在');
        }
        
        // 删除观众信息
        $sql = "DELETE FROM common_visitors WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        
        // 记录操作日志
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '删除常用观众信息',
            'common_visitors',
            "删除了观众信息：「{$visitor['name']}」",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(null, '删除成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('删除失败: ' . $e->getMessage(), 500);
    }
}

// 批量删除常用观众信息
function batchDeleteVisitors() {
    global $pdo, $admin;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $ids = $input['ids'] ?? [];
    
    if (empty($ids) || !is_array($ids)) {
        error('请选择要删除的观众信息');
    }
    
    try {
        $pdo->beginTransaction();
        
        $successCount = 0;
        $placeholders = str_repeat('?,', count($ids) - 1) . '?';
        
        // 获取观众信息用于日志
        $visitorSql = "SELECT name FROM common_visitors WHERE id IN ($placeholders)";
        $visitorStmt = $pdo->prepare($visitorSql);
        $visitorStmt->execute($ids);
        $visitors = $visitorStmt->fetchAll(PDO::FETCH_COLUMN);
        
        // 批量删除
        $sql = "DELETE FROM common_visitors WHERE id IN ($placeholders)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($ids);
        $successCount = $stmt->rowCount();
        
        // 记录操作日志
        $visitorNames = implode('、', $visitors);
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '批量删除常用观众信息',
            'common_visitors',
            "批量删除了{$successCount}个观众信息：{$visitorNames}",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(['success_count' => $successCount], "成功删除{$successCount}个观众信息");
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('批量删除失败: ' . $e->getMessage(), 500);
    }
}

// 获取统计信息
function getVisitorStats() {
    global $pdo;
    
    try {
        // 总体统计
        $totalSql = "SELECT 
                        COUNT(*) as total,
                        COUNT(DISTINCT user_id) as unique_users
                     FROM common_visitors";
        $totalStmt = $pdo->query($totalSql);
        $totalStats = $totalStmt->fetch(PDO::FETCH_ASSOC);
        
        // 按证件类型统计
        $typeSql = "SELECT 
                        id_type,
                        COUNT(*) as count
                    FROM common_visitors 
                    GROUP BY id_type 
                    ORDER BY count DESC";
        $typeStmt = $pdo->query($typeSql);
        $typeStats = $typeStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 最近7天新增统计
        $recentSql = "SELECT 
                        DATE(created_at) as date,
                        COUNT(*) as count
                      FROM common_visitors 
                      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
                      GROUP BY DATE(created_at)
                      ORDER BY date DESC";
        $recentStmt = $pdo->query($recentSql);
        $recentStats = $recentStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 热门观众（使用频率高）
        $popularSql = "SELECT 
                          cv.name,
                          cv.phone,
                          COUNT(*) as usage_count
                       FROM common_visitors cv
                       LEFT JOIN team_reservations tr ON cv.name = tr.contact_name AND cv.phone = tr.contact_phone
                       LEFT JOIN activity_applications aa ON cv.name = aa.contact_name AND cv.phone = aa.contact_phone
                       WHERE tr.id IS NOT NULL OR aa.id IS NOT NULL
                       GROUP BY cv.id
                       ORDER BY usage_count DESC
                       LIMIT 10";
        $popularStmt = $pdo->query($popularSql);
        $popularStats = $popularStmt->fetchAll(PDO::FETCH_ASSOC);
        
        success([
            'total_stats' => $totalStats,
            'type_stats' => $typeStats,
            'recent_stats' => $recentStats,
            'popular_visitors' => $popularStats
        ]);
        
    } catch (Exception $e) {
        error('获取统计信息失败: ' . $e->getMessage(), 500);
    }
}

// 导出常用观众信息
function exportVisitors() {
    global $pdo;
    
    try {
        // 构建查询条件（与列表查询相同）
        $where = "1=1";
        $params = [];
        
        if (isset($_GET['id_type']) && !empty($_GET['id_type'])) {
            $where .= " AND cv.id_type = ?";
            $params[] = $_GET['id_type'];
        }
        
        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $where .= " AND (cv.name LIKE ? OR cv.id_number LIKE ? OR cv.phone LIKE ?)";
            $params[] = '%' . $_GET['search'] . '%';
            $params[] = '%' . $_GET['search'] . '%';
            $params[] = '%' . $_GET['search'] . '%';
        }
        
        if (isset($_GET['user_id']) && is_numeric($_GET['user_id'])) {
            $where .= " AND cv.user_id = ?";
            $params[] = $_GET['user_id'];
        }
        
        // 查询数据
        $sql = "SELECT 
                    cv.name,
                    cv.id_type,
                    cv.id_number,
                    cv.phone,
                    cv.created_at,
                    u.nickname as user_nickname,
                    u.real_name as user_real_name
                FROM common_visitors cv
                LEFT JOIN users u ON cv.user_id = u.id
                WHERE $where
                ORDER BY cv.created_at DESC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $visitors = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 格式化导出数据
        $exportData = [];
        foreach ($visitors as $visitor) {
            $exportData[] = [
                'name' => $visitor['name'],
                'id_type' => $visitor['id_type'],
                'id_number' => $visitor['id_number'],
                'phone' => $visitor['phone'],
                'user_name' => $visitor['user_real_name'] ?: $visitor['user_nickname'] ?: '未知用户',
                'created_at' => $visitor['created_at']
            ];
        }
        
        success([
            'data' => $exportData,
            'total' => count($exportData),
            'export_time' => date('Y-m-d H:i:s')
        ]);
        
    } catch (Exception $e) {
        error('导出失败: ' . $e->getMessage(), 500);
    }
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'list':
                    getVisitorList();
                    break;
                case 'search':
                    getVisitorList(); // 搜索和列表使用相同逻辑，通过参数区分
                    break;
                case 'detail':
                    getVisitorDetail();
                    break;
                case 'stats':
                    getVisitorStats();
                    break;
                case 'export':
                    exportVisitors();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'PUT':
            updateVisitor();
            break;
            
        case 'DELETE':
            deleteVisitor();
            break;
            
        case 'POST':
            switch ($action) {
                case 'batch_delete':
                    batchDeleteVisitors();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>